package com.itheima.pinda.manager;

import com.itheima.pinda.file.dto.chunk.FileUploadDTO;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;

@Component
@Slf4j
public class WebUploader {

    public File getReadySpace(FileUploadDTO fileUploadDTO, String path) {
        //创建上传文件所需的文件夹
        if (!createFileFolder(path, false)) {
            return null;
        }
        //将上传的分片保存到此目录中
        String fileFolder = fileUploadDTO.getName();
        if (fileFolder==null){
            return null;
        }
        path+="/"+fileFolder;
        if (!createFileFolder(path,true)){
            return null;
        }

        String newFileName = String.valueOf(fileUploadDTO.getChunk());
        return new File(path,newFileName);
    }

    /**
     * 创建存放分片的临时文件夹
     *
     * @param path
     * @param hasTmp
     * @return
     */
    private boolean createFileFolder(String path, boolean hasTmp) {
        File tmpFile = new File(path);
        if (!tmpFile.exists()) {
            try {
                tmpFile.mkdirs();
            } catch (Exception e) {
                log.info("无法创建文件夹", e);
                return false;
            }
        }
        if (hasTmp) {
            tmpFile = new File(path + ".tmp");
            if (tmpFile.exists()) {
                return tmpFile.setLastModified(System.currentTimeMillis());
            } else {
                try {
                    tmpFile.createNewFile();
                } catch (IOException e) {
                    log.info("无法创建tmp文件", e);
                    return false;
                }
            }
        }
        return true;
    }
}
